import os
import shutil
import tempfile
from fastapi import APIRouter, UploadFile, File, HTTPException
from fastapi.responses import FileResponse
from typing import Optional
from pathlib import Path
from ...scripts.ppt_to_video import main as convert_ppt_to_video

router = APIRouter()

@router.post("/convert")
async def convert_ppt(
    file: UploadFile = File(...),
    azure_key: Optional[str] = None,
    voice: Optional[str] = None,
    local_voice: Optional[str] = None,
    sherpa_model: Optional[str] = None
):
    # 创建临时目录
    with tempfile.TemporaryDirectory() as temp_dir:
        try:
            # 保存上传的PPT文件
            ppt_path = os.path.join(temp_dir, file.filename)
            with open(ppt_path, "wb") as buffer:
                shutil.copyfileobj(file.file, buffer)
            
            # 设置输出路径
            output_path = os.path.join(temp_dir, "output.mp4")
            
            # 调用转换函数
            convert_ppt_to_video(
                ppt_path=ppt_path,
                output=output_path,
                azure_key=azure_key,
                voice=voice,
                local_voice=local_voice,
                sherpa_model=sherpa_model
            )
            
            # 返回转换后的视频
            return FileResponse(
                output_path,
                media_type="video/mp4",
                filename=Path(ppt_path).stem + ".mp4"
            )
            
        except Exception as e:
            raise HTTPException(
                status_code=500,
                detail=f"PPT转换失败: {str(e)}"
            )
